package com.zhanqiao.controller;

import com.zhanqiao.service.AdminService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
@WebServlet("/admin.do")
public class AdminController  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
                //创建工厂对象
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        // 创建文件解析器
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        //解决文件名乱码
        servletFileUpload.setHeaderEncoding("utf8");
        Object []objects=new Object[6];
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
//            DataSource dataSource= GetDataSourceUtil.getDataSource();
//            QueryRunner queryRunner=new QueryRunner(dataSource);
           
            int i=0;
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    objects[i++]=fileItem.getString("UTF8");
//                    queryRunner.update("insert into admin(aname) values('"+fileItem.getString("UTF8")+"')");
//                    System.out.println("表单数据" + fileItem.getFieldName() + ":" + fileItem.getString("UTF8"));
                } else {
                    System.out.println("不是表单数据.." + fileItem.getName());
                    String toPath = getServletContext().getRealPath("/upload");
                    String uuid = UUID.randomUUID().toString();
                    File toFile = new File(toPath + "/" + uuid + "_" + fileItem.getName());
                    if (!toFile.getParentFile().exists()) {
                        toFile.getParentFile().mkdir();
                    }
                    fileItem.write(toFile);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        AdminService adminService=new AdminService();
        try {
            adminService.getAdminData(objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}



